package com.my.config.ds.datarouting;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
@Aspect
@Component
@Order(value = 1)
public class DataSourceExchangeAspect {
    public DataSourceExchangeAspect() {
    }

    @Pointcut("execution(* *..*ServiceImpl.*(..))")
    public void serviceMethods() {

    }

    @Before("serviceMethods()")
    public void before(JoinPoint point) {
        Object target = point.getTarget();
        String method = point.getSignature().getName();
        Class<?>[] classz = target.getClass().getInterfaces();
        Class[] parameterTypes = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();

        try {
            Method m = classz[0].getMethod(method, parameterTypes);
            if(m != null && m.isAnnotationPresent(DataSourceKey.class)) {
                DataSourceKey key = (DataSourceKey)m.getAnnotation(DataSourceKey.class);
                DbContextHolder.setDataSourceKey(key.value());
            }
        } catch (Exception var8) {
            var8.printStackTrace();
        }

    }

    @AfterReturning(pointcut = "serviceMethods()")
    public void after(JoinPoint point) {
        Object target = point.getTarget();
        String method = point.getSignature().getName();
        Class<?>[] classz = target.getClass().getInterfaces();
        Class[] parameterTypes = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();

        try {
            Method m = classz[0].getMethod(method, parameterTypes);
            if(m != null && m.isAnnotationPresent(DataSourceKey.class)) {
                DbContextHolder.cleanDataSourceKey();
            }
        } catch (Exception var7) {
            var7.printStackTrace();
        }

    }
}